package com.zige.zige.bj_vr;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.zige.zige.R;
import com.zige.zige.activity.BaseActivity;
import com.zige.zige.activity.videoplay.MenuVideodetailActivity;
import com.zige.zige.constants.UrlConsts;
import com.zige.zige.dialog.PromptDialog;
import com.zige.zige.dialog.ZiGeShareDialog;
import com.zige.zige.pojo.UserInfo;
import com.zige.zige.pojo.VideoInfo;
import com.zige.zige.task.PostRequestTask;
import com.zige.zige.task.TaskExecutor;
import com.zige.zige.utils.ImageFuzzy;
import com.zige.zige.utils.SystemUtils;
import com.zige.zige.utils.ToastUtils;
import com.zige.zige.utils.VolleyImageUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Fei on 2016/3/11.
 */
public class BJVRVideoDetail extends BaseActivity implements View.OnClickListener {

    private RelativeLayout lay_video_content;//背景
    private ImageView img_videodetails_bg,img_lay_bg;//视频图片背景、大背景

    private TextView tv_video_title, tv_video_content;//视频标题
    private ImageView img_video_play, img_video_classification,img_share;//视频播放、视频分类标签
    private Button btn_user_prise;

    private ArrayList<VideoInfo> playList;
    private int currentPosition = 0;

    private String videoTitle,videoContent,videoImageUrl, videoId, videoUrl, isPraises;
    private UserInfo userInfo;
    private LinearLayout lay_backed;
    private int  mSize=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bjvr_detial);
        userInfo = application.getUserInfo();
        initView();

    }

    //手指按下的点为(x1, y1)手指离开屏幕的点为(x2, y2)
    float x1 = 0;
    float x2 = 0;
    float y1 = 0;
    float y2 = 0;

    private void initView() {
        tv_video_title = serchViewById(R.id.video_title);
        tv_video_content = serchViewById(R.id.tv_video_content);
        tv_video_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //继承了Activity的onTouchEvent方法，直接监听点击事件
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    //当手指按下的时候
                    x1 = event.getX();
                    y1 = event.getY();
                }
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    //当手指离开的时候
                    x2 = event.getX();
                    y2 = event.getY();
                    if ((y1 - y2 > 50) && (Math.abs(x2 - x1) <= (y1 - y2))) {
//                        ToastUtils.showToast(BJVRVideoDetail.this, "向上滑");
                    } else if ((y2 - y1 > 50) && (Math.abs(x2 - x1) <= (y2 - y1))) {
//                        ToastUtils.showToast(BJVRVideoDetail.this, "向下滑");
                    } else if ((x1 - x2 > 50) && (Math.abs(y2 - y1) < (x1 - x2))) {
                        onNext();

                    } else if ((x2 - x1 > 50) && (Math.abs(y2 - y1) < (x2 - x1))) {
//                        ToastUtils.showToast(BJVRVideoDetail.this, "下一个");
                        onBefore();
                    }
                }
                return true;
            }
        });

        img_videodetails_bg = serchViewById(R.id.img_videodetails_bg);
        img_lay_bg= serchViewById(R.id.img_lay_bg);
        img_video_classification = serchViewById(R.id.img_video_classification);
        img_video_play = serchViewById(R.id.img_video_play);
        img_video_play.setOnClickListener(this);
        btn_user_prise = serchViewById(R.id.btn_user_prise);
        btn_user_prise.setOnClickListener(this);
        img_share =serchViewById(R.id.img_share);
        img_share.setOnClickListener(this);
        lay_backed = serchViewById(R.id.lay_backed);
        lay_backed.setOnClickListener(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        MyAsync task = new MyAsync();
        task.execute(getIntent());
    }


    void onNext() {
        if (currentPosition >= playList.size() - 1) {
            ToastUtils.showToast(BJVRVideoDetail.this, "后面没有啦");
            return;
        }
        currentPosition++;
        if(playList.get(currentPosition).getType()==0){
            Intent intent = new Intent(BJVRVideoDetail.this, MenuVideodetailActivity.class);
            intent.putExtra("playList",playList);
            intent.putExtra("position",currentPosition);
            intent.putExtra("mSize",mSize);
            startActivity(intent);
            finish();
        }else {
            return;
        }
        getVideoDetils(String.valueOf(playList.get(currentPosition).getId()));

    }

    void onBefore() {
        if (currentPosition <= 0 ) {
            ToastUtils.showToast(BJVRVideoDetail.this, "前面没有啦");
            return;
        }
        currentPosition--;
        getVideoDetils(String.valueOf(playList.get(currentPosition).getId()));

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_share:
                sharesina();
                break;
            case R.id.btn_user_prise:
                if (application.isLogin()) {
                    setPressPraise(operate);
                } else {
                    PromptDialog dialog = new PromptDialog();
                    dialog.show(getFragmentManager(), "dialo");
                }
                break;
            case R.id.img_video_play:
                Intent intent = new Intent();
                intent.putExtra("playList",playList);
                intent.putExtra("position",currentPosition);
                intent.setClass(BJVRVideoDetail.this,BJVrPlayActivity.class);
                startActivity(intent);
                break;
            case R.id.lay_backed:
                finish();
                break;

        }
    }

    private void getVideoDetils(String vid) {
        HashMap<String, String> params = new HashMap<>();
        params.put("vid", vid);
        TaskExecutor.getInstance().execute(new PostRequestTask(params, BJVRVideoDetail.this, UrlConsts.VIDEO_DETILS) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int ret = object.getInt("code");
                    String msg = object.getString("message");
                    if (ret == 0000) {
                        object = object.getJSONObject("jxVideo");
                        videoTitle = object.getString("videoName");
                        tv_video_title.setText(videoTitle);
                        videoContent = object.getString("videoDesc");
                        tv_video_content.setText(videoContent);
                        videoImageUrl = object.getString("videoPicUrl");

                        VolleyImageUtils.displayImage(videoImageUrl, img_videodetails_bg, BJVRVideoDetail.this);
                        img_lay_bg.setImageBitmap(ImageFuzzy.convertToBlur(ImageFuzzy.GetLocalOrNetBitmap(videoImageUrl)));
//                        VolleyImageUtils.displayImage(videoImageUrl, img_lay_bg, BJVRVideoDetail.this);

                        videoUrl = object.getString("videoUrl");
                        videoId = object.getString("id");
                        isPraises = object.getString("praiseUserids");
                        if (application.isLogin()) {
                            if (isPraises.contains(userInfo.userID)) {
                                operate = 1;
                                btn_user_prise.setBackgroundResource(R.drawable.zan_selected);
                            } else {
                                btn_user_prise.setBackgroundResource(R.drawable.user_prise);
                                operate = 0;
                            }
                        } else {
                            btn_user_prise.setBackgroundResource(R.drawable.user_prise);
                        }

                    } else {
                        throw new Exception(msg);
                    }
                } catch (Exception e) {

                } finally {
                }
            }

            @Override
            protected void handleError() {
                super.handleError();
                closeLoadingDialog();
            }
        });
    }


    /***
     * 点赞
     *
     * @param operated
     */
    private int operate;
    private void setPressPraise(final int operated) {
        String deviceId = SystemUtils.getDeviceKey(BJVRVideoDetail.this);
        HashMap<String, String> params = new HashMap<>();
        params.put("deviceId", deviceId);
        params.put("uid", userInfo.userID);
        params.put("account", userInfo.phoneNumber);
        params.put("jxVideoId", videoId);
        params.put("operate", String.valueOf(operated));
        TaskExecutor.getInstance().execute(new PostRequestTask(params, BJVRVideoDetail.this, UrlConsts.VIDEO_PRAISE) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int ret = object.getInt("code");
                    String msg = object.getString("message");
                    if (ret == 0000) {
                        if (operated == 0) {
                            btn_user_prise.setBackgroundResource(R.drawable.zan_selected);
                            operate = 1;
                        }
                        if (operated == 1) {
                            btn_user_prise.setBackgroundResource(R.drawable.user_prise);
                            operate = 0;
                        }

                    } else {
                        closeLoadingDialog();
                        throw new Exception(msg);
                    }
                } catch (Exception e) {
                    ToastUtils.showToast(BJVRVideoDetail.this, e.getMessage());
//                    tv_check_error.setVisibility(View.VISIBLE);
                } finally {
                }
            }
        });
    }


    class MyAsync extends AsyncTask<Intent, Integer, String> {

        @Override
        protected String doInBackground(Intent... params) {
            Intent intent = params[0];
            playList = (ArrayList<VideoInfo>) intent.getSerializableExtra("playList");
            currentPosition = intent.getIntExtra("position", 0);
            mSize = intent.getIntExtra("mSize",0);
            if (playList == null || playList.size() < 1) {
                ToastUtils.showToast(BJVRVideoDetail.this, "无视频数据");
                finish();
            }

            getVideoDetils(playList.get(currentPosition).getId());

            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            if (100 == values[0])
            super.onProgressUpdate(values);
        }

    }

    private UMImage shareVideoImageUrl;
    private String shareVideoUrl;
    private void sharesina() {
        ZiGeShareDialog dialog = new ZiGeShareDialog();
        dialog.setSharelister(zigeshareLister);
        dialog.show(getFragmentManager(), "dialog");

        if (TextUtils.isEmpty(videoTitle)) {
            videoTitle = "VR小伴马";
        }

        shareVideoUrl = UrlConsts.SHARE_VIDEIO_URL + videoId;
        shareVideoImageUrl = new UMImage(BJVRVideoDetail.this, videoImageUrl);
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            com.umeng.socialize.utils.Log.d("plat", "platform" + platform);
            Toast.makeText(BJVRVideoDetail.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(BJVRVideoDetail.this,platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(BJVRVideoDetail.this,platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };


    private ZiGeShareDialog.ZigeshareLister zigeshareLister = new ZiGeShareDialog.ZigeshareLister() {
        @Override
        public void shareSina() {
            new ShareAction(BJVRVideoDetail.this).setPlatform(SHARE_MEDIA.SINA).setCallback(umShareListener)
                    .withTitle(videoTitle)
                    .withText("分享给大家一个好看的视频：")
                    .withMedia(shareVideoImageUrl)
                    .withTargetUrl(shareVideoUrl)
                    .share();
        }

        @Override
        public void shareWeiXin() {
            new ShareAction(BJVRVideoDetail.this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                    .withTitle(videoTitle)
                    .withText("分享给大家一个好看的视频：")
                    .withMedia(shareVideoImageUrl)
                    .withTargetUrl(shareVideoUrl)
                    .share();
        }

        @Override
        public void shareWeiXinCircle() {
            new ShareAction(BJVRVideoDetail.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                    .withTitle(videoTitle)
                    .withText("分享给大家一个好看的视频：")
                    .withMedia(shareVideoImageUrl)
                    .withTargetUrl(shareVideoUrl)
                    .share();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
